package com.xiaoxing.salesclient.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.salesclient.di.component.DaggerDingGouDanComponent;
import com.xiaoxing.salesclient.di.module.DingGouDanModule;
import com.xiaoxing.salesclient.mvp.contract.DingGouDanContract;
import com.xiaoxing.salesclient.mvp.model.entity.ProductOrder;
import com.xiaoxing.salesclient.mvp.presenter.DingGouDanPresenter;
import com.xiaoxing.salesclient.mvp.ui.adapter.DingGouDanAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import xiaoxing.com.salesclient.R;
import xiaoxing.com.salesclient.R2;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class DingGouDanFragment extends BaseFragment<DingGouDanPresenter> implements DingGouDanContract.View, OnRefreshListener {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;

    @BindView(R2.id.title)
    TextView tvTitle;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.tv_chan_pin_jia_mu_biao)
    TextView tvChanPinJiaMuBiao;
    @BindView(R2.id.tv_liao_cheng_jia_mu_biao)
    TextView tvLiaoChengJiaMuBiao;
    Unbinder unbinder;
    private DingGouDanAdapter mAdapter;
    private List<ProductOrder.DataBean> mDataBeanList = new ArrayList<>();
    private int type = 0;

    public static DingGouDanFragment newInstance() {
        DingGouDanFragment fragment = new DingGouDanFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDingGouDanComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .dingGouDanModule(new DingGouDanModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ding_gou_dan, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        toolbar.setNavigationIcon(null);
        tvTitle.setText("訂購單");
        initRefreshLayout();
        initRecyclerView();
        initEmpty();

    }

    private void getProductOrder() {

        if (mSharedPreferencesHelper.getString(BaseConstants.IS_STAFF).equals("0")) {//0是用户，1是员工
            mPresenter.productOrder(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
        } else {
            mPresenter.productOrderAll(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
        }
    }


    private void getCourseOrder() {
        if (mSharedPreferencesHelper.getString(BaseConstants.IS_STAFF).equals("0")) {//0是用户，1是员工
            mPresenter.courseOrder(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
        } else {
            mPresenter.courseOrderAll(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
        }
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new DingGouDanAdapter(getActivity(), mDataBeanList));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.no_data);
        empty_text.setTextColor(getResources().getColor(R.color.public_no_data));
        empty_text.setText("暫無消息,下拉更新");
    }


    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        if (type == 0) {
            getProductOrder();
        } else {
            getCourseOrder();
        }

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {
        mRefreshLayout.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }


    @OnClick({R2.id.tv_chan_pin_jia_mu_biao, R2.id.tv_liao_cheng_jia_mu_biao})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_chan_pin_jia_mu_biao) {
            tvLiaoChengJiaMuBiao.setTextColor(Color.parseColor("#999999"));
            tvChanPinJiaMuBiao.setTextColor(getResources().getColor(R.color.public_black));
            type = 0;
            getProductOrder();
        } else if (i == R.id.tv_liao_cheng_jia_mu_biao) {
            tvLiaoChengJiaMuBiao.setTextColor(getResources().getColor(R.color.public_black));
            tvChanPinJiaMuBiao.setTextColor(Color.parseColor("#999999"));
            type = 1;
            getCourseOrder();
        }
    }

    @Override
    public void productOrderSucessed(ProductOrder productOrder) {
        setData(productOrder);

    }

    @Override
    public void productOrderAllSucessed(ProductOrder productOrder) {
        setData(productOrder);
    }

    private void setData(ProductOrder productOrder) {

        if (productOrder != null && productOrder.getData() != null && productOrder.getData().size() > 0) {
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
            mDataBeanList.clear();
            mDataBeanList.addAll(productOrder.getData());
            mAdapter.notifyDataSetChanged();
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    @Override
    public void courseOrderSucessed(ProductOrder productOrder) {
        setData(productOrder);
    }

    @Override
    public void courseOrderAllSucessed(ProductOrder productOrder) {
        setData(productOrder);
    }
}
